package com.childenglish.controller;

import com.childenglish.service.SpeechRecognitionService;
import com.childenglish.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/speech")
public class SpeechController {

    @Autowired
    private SpeechRecognitionService speechService;

    /**
     * 语音识别接口
     */
    @PostMapping("/recognize")
    public R recognizeSpeech(@RequestParam("audio") MultipartFile audioFile) {
        try {
            if (audioFile.isEmpty()) {
                return R.error("音频文件不能为空");
            }

            Map<String, Object> result = speechService.processSpeech(audioFile);
            return R.ok("语音识别成功").data(result);

        } catch (Exception e) {
            return R.error("语音识别失败: " + e.getMessage());
        }
    }

    /**
     * 发音评估接口
     */
    @PostMapping("/evaluate")
    public R evaluatePronunciation(
            @RequestParam("text") String text,
            @RequestParam("audio") MultipartFile audioFile) {
        try {
            Map<String, Object> result = speechService.evaluatePronunciation(text, audioFile);
            return R.ok("发音评估完成").data(result);

        } catch (Exception e) {
            return R.error("发音评估失败: " + e.getMessage());
        }
    }

    /**
     * 实时语音流处理
     */
    @PostMapping("/stream")
    public R handleSpeechStream(@RequestBody Map<String, Object> streamData) {
        try {
            // 模拟实时语音处理
            Map<String, Object> result = new HashMap<>();
            result.put("sessionId", streamData.get("sessionId"));
            result.put("text", "实时识别文本");
            result.put("isFinal", true);

            return R.ok("实时语音处理成功").data(result);

        } catch (Exception e) {
            return R.error("实时语音处理失败: " + e.getMessage());
        }
    }
}